import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import error from '@feidao/web/atom/browser/msgbox/error';
import call_service from '@feidao/web/atom/browser/msg/call-service';
import { spaceid, send_msg as url } from './config';
import nodejs from '@feidao/web/atom/browser/msg/nodejs';
import get from '@feidao/web/atom/core/local/get';
import fire from '@feidao/web/atom/browser/msg/fire';


export default async function (fd: IFeidaoAiBrowserComponent, ...args: any[]) {

	//确定
	const npn_dom = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="npn"]');
	const dom = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="verificationcode"]');

	const value = dom.value;
	const npn_value = npn_dom.value;

	const regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";

	const phone = get(fd, 'phone');
	const usercode = get(fd, 'usercode');

	if (!npn_value.match(regex)) {
		await error('请输入正确的手机号');
		return;
	}

	if (!value) {
		await error('填写验证码');
		return;
	}

	if (npn_value != phone) {
		await error('请重新获取验证码');
		dom.value = '';
		return;
	}


	const param = {
		phone: npn_value,
		spaceid,
		strategyid: '32fce1f7-b1c3-49b0-b191-828214d7fbae',
		systemid: '12',
		verifycode: value
	};



	const res = await call_service<{ code: number, msg: string }>(url, 'busiservice.flippedclass.verifyphoneverifycode', param, false, false);

	if (res.msg == "验证码正确") {

		const res = await call_service<{ code: number, msg: string }>(url, 'busiservice.flippedclass.bandphone', {
			phone,
			spaceid: "flippedclass",
			usercode
		}, false, false);

		if (res.msg == '手机号绑定成功') {

			await nodejs(url, 'phone_upd', { usercode, phone }, false, false);

			fd.data.node.querySelector('[data-feidao-zjc="08"]').classList.add('display-n');
			fd.data.node.classList.add('display-n');
			npn_dom.value = '';
			dom.value = '';
			fire('zjc-000001', 'ec-001', 'success', '手机号更换成功');
			return;

		} else {
			await error('更换手机号失败');
			return;

		}

	} else {
		await error(`${res.msg}`);
		return;
	}
}

